//
//  GTProgressView.m
//  JinduExample
//
//  Created by tyndog on 2017/1/16.
//  Copyright © 2017年 GT. All rights reserved.
//

#import "GTProgressView.h"
#import <CoreText/CoreText.h>

//通用宏定义
#define kWidth (self.bounds.size.width)
#define kHeight (self.bounds.size.height)
#define kRadius 10
//中心点距离底部的距离
#define kMarginBottom (15)
#define kCenterY (kHeight - kMarginBottom)

//进度条长度
#define kProgressWidth (kWidth - 2 * kRadius)

//圆形的宏定义
#define kLineWidth (2)
#define kCircleRadius (kRadius + kLineWidth)
//圆形开始的点
#define kDefaultX kRadius
//虚线高度
#define kDashHeight (50)

//普通字体
#define kNorFont (11.0f)
//百分号字体
#define kOrangeFont (13.0f)

#define kOrangeColor ([UIColor colorWithRed:1.0f green:0.5f blue:0.4f alpha:1.0])

@implementation GTProgressView

- (void)drawRect:(CGRect)rect{
    [super drawRect:rect];
    CGContextRef context = UIGraphicsGetCurrentContext();
    //保存干净的上下文
    CGContextSaveGState(context);
    [self drawBottom:context];
    if (_progress < 0.0f || _progress > 1.0f){
        return;
    }
    [self drawGradient:context];
    //恢复保存的干净的上下文
    CGContextRestoreGState(context);
    CGContextSaveGState(context);
    [self drawCircle:context];
    //画虚线
    [self drawDash:context];
    //画字
    CGContextRestoreGState(context);
    [self drawText:context];
}

- (void)drawBottom: (CGContextRef)context{
    //1. 绘制底部
    CGContextAddArc(context, kRadius , kCenterY, kRadius, M_PI_2, -M_PI_2, 0);
    CGContextAddArc(context, kWidth - kRadius, kCenterY, kRadius, -M_PI_2, M_PI_2, 0);
    [[UIColor lightGrayColor] setFill];
    CGContextDrawPath(context, kCGPathFill);
}

- (void)drawGradient:(CGContextRef)context{
    
    
    CGFloat endPointX = (kWidth - kRadius) * _progress;
    //绘制进度渐变区域
    CGContextAddArc(context, kDefaultX, kCenterY, kRadius, M_PI_2, -M_PI_2, 0);
    CGContextAddArc(context, endPointX, kCenterY, kRadius, -M_PI_2, M_PI_2, 0);
    
    CGGradientRef myGradient;
    CGColorSpaceRef myColorspace;
    size_t num_locations = 2;
    CGFloat locations[2] = { 0.0, 1.0 };
    CGFloat components[8] = {0.8, 0.8, 0.3, 1.0, // Start color
        1.0, 0.5, 0.4, 1.0}; // End color
    myColorspace = CGColorSpaceCreateWithName(kCGColorSpaceGenericRGB);
    myGradient = CGGradientCreateWithColorComponents (myColorspace, components,locations, num_locations);
    CGPoint myStartPoint, myEndPoint;
    CGFloat myStartkRadius, myEndkRadius;
    myStartPoint.x = kDefaultX;
    myStartPoint.y = kCenterY;
    myEndPoint.x = kWidth * _progress + kDefaultX;
    myEndPoint.y = kCenterY;
    myStartkRadius = kRadius;
    myEndkRadius = kRadius;
    
    //为了保存进度，需要裁剪
    CGContextClip(context);
    
    CGContextDrawRadialGradient (context,
                                 myGradient,
                                 myStartPoint,
                                 myStartkRadius,
                                 myEndPoint,
                                 myEndkRadius,
                                 kCGGradientDrawsAfterEndLocation
                                 );
    //释放内存
    CGGradientRelease(myGradient);
    CGColorSpaceRelease(myColorspace);
}

- (void)drawCircle:(CGContextRef)context{

    CGFloat centerX = kProgressWidth * _progress + kDefaultX;
    //添加阴影
    drawShadow(context);
    //画圆型
    CGContextAddArc(context, centerX, kCenterY, kCircleRadius, 0.0f, 2 * M_PI, 0);
    CGContextSetLineWidth(context, kLineWidth);
    [kOrangeColor setFill];
    [[UIColor whiteColor] setStroke];
    CGContextDrawPath(context, kCGPathFillStroke);

}

//制造阴影
static void drawShadow(CGContextRef context){
    
    CGSize          myShadowOffset = CGSizeMake (0.0,  0.0);
    CGFloat         myColorValues[4] = {1.0, 1.0, 1.0, 1.0};
    CGColorRef      myColor;
    CGColorSpaceRef myColorSpace;
    CGContextSetShadow (context, myShadowOffset, 5.0);
    myColorSpace = CGColorSpaceCreateDeviceRGB ();
    myColor = CGColorCreate(myColorSpace, myColorValues);
    CGContextSetShadowWithColor (context, myShadowOffset, 5.0, myColor);
    //释放内存
    CGColorRelease (myColor);
    CGColorSpaceRelease (myColorSpace);
}
//画虚线
- (void)drawDash:(CGContextRef)context{
    
    CGFloat lenghts[2] = {2, 3};
    CGFloat startX,startY, endX, endY;
    startX = kDefaultX + _progress * kProgressWidth;
    
    startY = kHeight - kMarginBottom - kRadius - kLineWidth - kDashHeight;
    endX = startX;
    endY = startY + kDashHeight;
    CGContextMoveToPoint(context, startX, startY);
    CGContextAddLineToPoint(context, endX, endY);
    CGContextSetLineDash(context, 0.0f, lenghts, 2);
    
    CGContextSetLineWidth(context, 5);
    [kOrangeColor setStroke];
    CGContextDrawPath(context, kCGPathStroke);
}

- (void)drawText:(CGContextRef)context{
    
    CGContextTranslateCTM(context, 0, self.bounds.size.height);
    CGContextScaleCTM(context, 1.0, -1.0);
    CGContextSetTextMatrix(context, CGAffineTransformIdentity);
    
    //把浮点数转成百分比
    NSString *numStr = [NSString stringWithFormat:@"%.2f", _progress * 100];
    NSString *baiStr = [self subString:numStr];
    
    CGMutablePathRef path = CGPathCreateMutable();
    CGRect bounds = CGRectMake(0, 0, kWidth, kHeight);//[self text:baiStr];
    CGPathAddRect(path, NULL, bounds );
    
    NSString *newStr = [NSString stringWithFormat:@"超越%@学校",baiStr];
    CFStringRef textString = (__bridge CFStringRef)newStr;
    
    CFMutableAttributedStringRef attrString =
    CFAttributedStringCreateMutable(kCFAllocatorDefault, 0);
    
    CFAttributedStringReplaceString (attrString, CFRangeMake(0, 0),
                                     textString);
    CGColorSpaceRef rgbColorSpace = CGColorSpaceCreateDeviceRGB();
    CGFloat components[] = { 1.0, 0.5, 0.4, 1.0 };
    CGColorRef red = CGColorCreate(rgbColorSpace, components);
    CGColorSpaceRelease(rgbColorSpace);
    CTFontRef norFont = CTFontRefCTFontCreateFromUIFont([UIFont systemFontOfSize:kNorFont]);
    CFAttributedStringSetAttribute(attrString, CFRangeMake(0, [newStr length]), kCTFontAttributeName, norFont);
    
    
    CGFloat lenght = [baiStr length];
    CTFontRef orangeFont = CTFontRefCTFontCreateFromUIFont([UIFont systemFontOfSize:kOrangeFont]);
    CFAttributedStringSetAttribute(attrString, CFRangeMake(2, lenght), kCTFontAttributeName, orangeFont);
    CFAttributedStringSetAttribute(attrString, CFRangeMake(2, lenght),
                                   kCTForegroundColorAttributeName, red);
    
    CTFramesetterRef framesetter =
    CTFramesetterCreateWithAttributedString(attrString);
    CFRelease(attrString);

    CTFrameRef frame;
    frame = CTFramesetterCreateFrame(framesetter,CFRangeMake(0, 0),
                                     path,NULL
                                     );
    
    CTFrameDraw(frame, context);
    CFRelease(frame);
    CFRelease(path);
    CFRelease(framesetter);
}
- (NSString *)subString:(NSString *)numStr{
    
    NSInteger count = 0;
    NSInteger lenght = [numStr length];
    for (NSInteger i = lenght - 1; i >= 0; i--) {
        @autoreleasepool {
            NSRange range = NSMakeRange(i, 1);
            NSString *subStr = [numStr substringWithRange:range];
            if ([subStr isEqualToString:@"0"]) {
                count++;
            }else {
                if([subStr isEqualToString:@"."]){
                    count++;
                }
                break;
            }
        }
    }
    NSRange range = NSMakeRange(0, lenght - count);
    return [NSString stringWithFormat:@"%@%%",[numStr substringWithRange:range]];
}

//UIFont 转 CTFontRef
static CTFontRef CTFontRefCTFontCreateFromUIFont(UIFont *font)
{
    CTFontRef ctFont =CTFontCreateWithName((CFStringRef)font.fontName,
                                           font.pointSize,
                                           NULL);
    return ctFont;
}

//计算
- (CGRect)text:(NSString *)orangeStr{
    
    CGSize norSize = [self getAttributeSizeWithText:@"超越学校" font:kNorFont];
    CGSize orangeSize = [self getAttributeSizeWithText:orangeStr font:kOrangeFont];
    
    CGFloat x,y,w,h;
    
    w = norSize.width +  orangeSize.width;
    h = orangeSize.height;
    x = kDefaultX + _progress * kProgressWidth - w;
    y = kHeight - kMarginBottom - kRadius - kLineWidth - kDashHeight;
    
    return CGRectMake(x, y, w, h);
}
//计算文字size
- (CGSize) getAttributeSizeWithText:(NSString *)text font:(CGFloat)font
{
    CGSize maxSize = CGSizeMake(MAXFLOAT, MAXFLOAT);
    
    CGSize realSize = [text boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:@{NSFontAttributeName: [UIFont systemFontOfSize:font]} context:nil].size;
    
    return realSize;
}

- (void)setProgress:(CGFloat)progress{
    _progress = progress;
    [self setNeedsDisplay];
}


@end
